<template>
	<view class="page">
		<!-- 课程信息 -->
		<view class="course-info">
			<view class="gym-location">
				<text class="location-text">场馆：{{dataInfo.venueName || ''}}</text>
			</view>
			<view class="booking-date">
				<text class="date-text">预约时间：{{ paramObj.selectedDate || ''}}</text>
			</view>
			<!-- 教练信息 -->
			<view class="coach-info">
				<image class="coach-avatar" :src="dataInfo.faceImgUrl" mode="aspectFill"></image>
				<view class="coach-details">
					<text class="coach-name">{{dataInfo.name || ''}}</text>
					<view class="coach-price">
						<text class="price-symbol">¥</text>
						<text class="price-amount">{{dataInfo.teachPrice || ''}}</text>
						<text class="price-unit">/节</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 选择时间 -->
		<view class="time-selection">
			<view class="section-title">选择时间</view>
			
			<!-- 时间段网格 -->
			<view class="time-grid">
				<view 
					class="time-slot" 
					:class="{ 
						'selected': selectedTimeIndex === index,
						'disabled': slot.disabled,
						'unavailable': slot.status === 'unavailable'
					}"
					v-for="(slot, index) in timeSlots" 
					:key="index"
					@click="selectTime(index)"
				>
					<text class="time-text">{{ slot.time }}</text>
				</view>
			</view>
		</view>
		
		<!-- 底部确定按钮 -->
		<view class="bottom-action">
			<!-- 提示信息 -->
			<view class="warning-notice">
				<wd-icon name="warning" color="#ff6b35" size="14px"></wd-icon>
				<text class="warning-text">最少购买一个小时,不足一小时按一小时计算</text>
			</view>
			
			<!-- 确定按钮 -->
			<view class="confirm-btn" :class="{ disabled: selectedTimeIndex === -1 }" @click="confirmBooking">
				<text class="btn-text">确定</text>
			</view>
		</view>
		<wd-status-tip v-if="timeSlots.length == 0" image="/static/viewNull.png"  :image-size="{ height: 50,  width: 50}" tip="暂无内容" />
		<fui-loading type="col" v-if="loadActive" :isFixed="true" :isMask="true"></fui-loading>
	</view>
</template>

<script setup>
	/**
	 * ==================== 数据定义 ====================
	 */
	
	// 当前选中的时间段索引
	const selectedTimeIndex = ref(-1) // -1表示未选择任何时间段
	const selectedTimeId = ref('');
	const selectedTimeTime = ref('');
	const loadActive = ref(false);
	const paramObj = ref({});
	const dataInfo = ref({});
	// 课程信息数据
	const courseInfo = ref()
	// 表单数据
	const formData = ref({
		name: '',           // 姓名
		mobile: '',          // 手机号码
		idcard: '',         // 身份证号码
		urgentLinker: '', // 紧急联系人电话
		faceImgUrl: '',       // 人脸照片
		hasOldFaceImg: 0       // 是否有历史人脸
	})
	
	// 时间段数据 - 模拟后台返回的数据，包含状态控制
	const timeSlots = ref([])
	
	/**
	 * ==================== 方法定义 ====================
	 */
	
	
	/**
	 * 选择时间段
	 * @param {number} index - 时间段的索引
	 */
	const selectTime = (index) => {
		const slot = timeSlots.value[index]
		
		// 如果时间段被禁用或不可用，则不允许选择
		if (slot.disabled || slot.status === 'unavailable') {
			uni.showToast({
				title: '该时间段不可预约',
				icon: 'none',
				duration: 1500
			})
			return
		}
		
		// 设置选中的时间段
		selectedTimeIndex.value = index;
		selectedTimeId.value = slot.id;
		selectedTimeTime.value = slot.time;

	}
	
	/**
	 * 确认预约- 跳转到购买资料填写页面

	 */
	const confirmBooking = () => {
		// 检查是否选择了时间段
		if (selectedTimeIndex.value === -1) {
			uni.showToast({
				title: '请选择预约时间',
				icon: 'none',
				duration: 1500
			})
			return
		}
		
		const selectedSlot = timeSlots.value[selectedTimeIndex.value]
		const param = {
			facePohoto:dataInfo.value.faceImgUrl,
			faceName:dataInfo.value.name,
			teachPrice:dataInfo.value.teachPrice,
			selectedTimeTime:selectedTimeTime.value,
			configIds:selectedTimeId.value,
			dateType:paramObj.value.dateType,
			teacherUserId:paramObj.value.id,
		}
		if(formData.value?.faceImgUrl){//有人脸直接购买
			const param2 = {
				...param,
				...formData.value,
			}
			uni.redirectTo({
				url: `/pagesA/view/course/pay?param=${JSON.stringify(param2)}`
			})
		}else{
			// 跳转到购买资料填写页面
			uni.navigateTo({
				url: `/pagesA/view/course/dataCourse?param=${JSON.stringify(param)}`
			})		
		}
	}
	
	/**
	 * 初始化时间段数据
	 * 从后台获取可用的时间段信息
	 */
	const initTimeSlots = async () => {
		loadActive.value = true;
		uni.api.getPrivateTrainersDetail({
			businessId:paramObj.value.id,
			classType:1,
			dateType:paramObj.value.dateType,
		}).then(res => {
		  if (res.code == 0) {
			dataInfo.value = res.data || {};
			// 处理接口返回的数据
			const processedData = (res.data?.venueTimeConfigRespList || []).map(item => {
				return {
					...item,
					// 拼接时间显示：startAt-endAt
					time: `${item.startAt}-${item.endAt}`,
					// 根据 canUse 字段设置状态：0=可用，1=无法使用
					status: item.canUse === 0 ? 'available' : 'unavailable',
					disabled: item.canUse === 1
				}
			});
			timeSlots.value = processedData;
			loadActive.value = false;
			selectedTimeIndex.value = -1;
		  }
		});
	}
	
	const getUser = ()=>{
		uni.api.getNewFaceImg().then(res => {
		  if (res.code == 0) {
			// 对象遍历 有值 赋值
			Object.keys(res.data).forEach(key => {
				if (res.data[key]) {
					formData.value[key] = res.data[key]
				}
			})
			formData.value.hasOldFaceImg = res.data?.faceImgUrl?1:0;
		  }
		});
	}
	/**
	 * ==================== 生命周期 ====================
	 */
	
	/**
	 * 页面挂载完成后的初始化操作
	 */
	onLoad((opt) => {
		const param = JSON.parse(opt.param);
		paramObj.value = param;
		getUser();
	})
	onShow(() => {
		// 初始化时间段数据
		initTimeSlots();
	})	
		
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding: 0;
	}

	// 课程信息
	.course-info {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		
		.gym-location {
			margin-bottom: 16rpx;
			
			.location-text {
				font-size: 28rpx;
				color: #666;
			}
		}
		
		.booking-date {
			margin-bottom: 30rpx;
			
			.date-text {
				font-size: 28rpx;
				color: #666;
			}
		}
		
		.coach-info {
			display: flex;
			align-items: center;
			
			.coach-avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				margin-right: 24rpx;
			}
			
			.coach-details {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.coach-name {
					font-size: 32rpx;
					color: #333;
					font-weight: 500;
				}
				
				.coach-price {
					display: flex;
					align-items: baseline;
					
					.price-symbol {
						font-size: 24rpx;
						color: #ff6b35;
						margin-right: 4rpx;
					}
					
					.price-amount {
						font-size: 36rpx;
						color: #ff6b35;
						font-weight: 600;
					}
					
					.price-unit {
						font-size: 24rpx;
						color: #ff6b35;
						margin-left: 4rpx;
					}
				}
			}
		}
	}

	// 选择时间
	.time-selection {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 120rpx; // 为底部按钮留出空间
		
		.section-title {
			font-size: 32rpx;
			color: #333;
			font-weight: 500;
			margin-bottom: 30rpx;
		}
		
		.time-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;
			
			.time-slot {
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border: 2rpx solid #e0e0e0;
				border-radius: 8rpx;
				background-color: #fff;
				transition: all 0.3s ease;
				
				&.selected {
					background-color: #000;
					border-color: #000;
					
					.time-text {
						color: #fff;
					}
				}
				
				&.disabled,
				&.unavailable {
					background-color: #f5f5f5;
					border-color: #e0e0e0;
					
					.time-text {
						color: #ccc;
					}
				}
				
				.time-text {
					font-size: 26rpx;
					color: #333;
				}
			}
		}
	}

	// 底部操作区
	.bottom-action {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx 40rpx;
		border-top: 1rpx solid #f0f0f0;
		
		.warning-notice {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			
			.warning-text {
				margin-left: 8rpx;
				font-size: 24rpx;
				color: #ff6b35;
			}
		}
		
		.confirm-btn {
			width: 100%;
			height: 88rpx;
			background-color: #000 !important;
			border-radius: 48rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s ease;
			
			&.disabled {
				background-color: #ccc;
			}
			
			.btn-text {
				font-size: 32rpx;
				color: #fff;
				font-weight: 500;
			}
		}
	}
</style>